package com.xingda.packing.minitor.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xingda.packing.common.DateTimeUtils;
import com.xingda.packing.common.dto.PageDto;
import com.xingda.packing.minitor.dto.PkLogDto;
import com.xingda.packing.minitor.dto.UserInfo;
import com.xingda.packing.minitor.entity.PkLog;
import com.xingda.packing.minitor.mapper.PkLogMapper;
import com.xingda.packing.minitor.service.IpkLogService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;

@Service
public class PkLogServiceImpl extends ServiceImpl<PkLogMapper, PkLog> implements IpkLogService {
    @Override
    public Page<PkLogDto> getPkLogPage(PageDto dto) {
        if (dto.getCurrent() == 0) {
            dto.setCurrent(1);
        }
        if (dto.getPagesize() == 0) {
            dto.setPagesize(10);
        }
        Page<PkLog> page = new Page<>(dto.getCurrent(), dto.getPagesize());
        LambdaQueryWrapper<PkLog> queryWrapper = Wrappers.lambdaQuery();
        Date start = DateTimeUtils.toDate(dto.getStart());
        queryWrapper.ge(Objects.nonNull(start), PkLog::getCreateTime, start);

        Date end = DateTimeUtils.toDate(dto.getEnd());
        queryWrapper.le(Objects.nonNull(end), PkLog::getCreateTime, end);

        queryWrapper.like(StringUtils.hasText(dto.getKeyword()), PkLog::getOperation, dto.getKeyword());
        queryWrapper.orderByDesc(PkLog::getCreateTime);
        this.baseMapper.selectPage(page, queryWrapper);
        Page<PkLogDto> pkLogDtoPage = new Page<>();
        BeanUtils.copyProperties(page, pkLogDtoPage);
        List<PkLogDto> dtos = new ArrayList<>();
        List<PkLog> pkLogs = page.getRecords();
        pkLogs.forEach(l -> {
            PkLogDto pkLogDto = new PkLogDto();
            BeanUtils.copyProperties(l, pkLogDto);
            dtos.add(pkLogDto);
        });
        pkLogDtoPage.setRecords(dtos);
        return pkLogDtoPage;
    }

    @Override
    public void saveLog(UserInfo userInfo) {
        PkLog pkLog = new PkLog();
        pkLog.setUsername(userInfo.getRealname());
        pkLog.setNumber(userInfo.getUsername());
        pkLog.setIsSuccess(1);
        pkLog.setCreateTime(new Date());
        pkLog.setOperation(userInfo.getOperation());
        pkLog.setCompany(userInfo.getCompany());
        this.baseMapper.insert(pkLog);
    }
}
